package com.shwread.android.qysw.activity.task;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.GlideUtil;
import com.NewActionHelp;
import com.ciko.code.base.BaseActicity;
import com.ciko.code.views.multi_image_selector.MultiImageSelectorActivity;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.QyReaderApp;
import com.shwread.android.qysw.bean.task.SubItemBean;
import com.shwread.android.qysw10000242.R;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.base.TextHttpResponseHandler;
import com.shwread.httpsdk.util.NetUtil;

import org.apache.http.Header;

import java.io.FileNotFoundException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import logic.util.Util;
import logic.util.Utils;

/**
 * 个人申报活动
 */
public class AskPersonalTaskActivity extends BaseActicity {
    private static final int REQUEST_IMAGE = 7;
    private ArrayList<String> selectedPictureAll = new ArrayList<>();

    private List<SubItemBean> subItemBeanList = new ArrayList<>();
    private SubItemBean subItemBean;
    private String voucherData;

    /**
     * 活动名称
     */
    private EditText etTaskName;
    /**
     * 分项
     */
    private TextView tvTaskSubItem;
    /**
     * 类别
     */
    private TextView tvTaskCategory;
    /**
     * 指数类型
     */
    private TextView tvTaskType;
    /**
     * 活动分值
     */
    private TextView tvTaskValue;
    /**
     * 上传凭证
     */
    private ImageView imgUploadTestimony;
    /**
     * 确定申报
     */
    private Button btnAskTask;
    private PopupWindow moreAccountPup;

    @Override
    protected void initTopBar() {
        setTitle("个人申报活动");
        enableNavLeftImg();
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_ask_personal_task);
    }

    @Override
    protected void initView() {
        etTaskName = findViewByID(R.id.et_task_name);
        tvTaskSubItem = findViewByID(R.id.tv_task_sub_item);
        tvTaskCategory = findViewByID(R.id.tv_task_category);
        tvTaskType = findViewByID(R.id.tv_task_type);
        tvTaskValue = findViewByID(R.id.tv_task_value);
        imgUploadTestimony = findViewByID(R.id.img_upload_testimony);
        btnAskTask = findViewByID(R.id.btn_ask_task);
    }

    @Override
    protected void initAdapter() {

    }

    @Override
    protected void initDates() {
        NewActionHelp.qryIndexList(this, new ObjectHttpResponseHandler<ArrayList<SubItemBean>>() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                Log.e("sss", "失败--" + s);
            }

            @Override
            public void onSuccess(int i, Header[] headers, ArrayList<SubItemBean> subItemBeanArrayList, String s) {
                Log.e("sss", "成功--" + s);
                if (subItemBeanArrayList != null) {
                    subItemBeanList = subItemBeanArrayList;
                }
            }

            @Override
            public Type getType() {
                return new TypeToken<ArrayList<SubItemBean>>() {
                }.getType();
            }
        });
    }

    @Override
    protected void initListener() {
        tvTaskSubItem.setOnClickListener(this);
        imgUploadTestimony.setOnClickListener(this);
        btnAskTask.setOnClickListener(this);
        etTaskName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 50) {
                    Util.showToast(QyReaderApp.application, "超过了字数限制");
                    CharSequence sequence = s.subSequence(0, 50);
                    etTaskName.setText(sequence);
                    etTaskName.setSelection(sequence.length());
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_task_sub_item://分项
                showDropPop(v);
                break;
            case R.id.img_upload_testimony://上传凭证
                selectImg();
                break;
            case R.id.btn_ask_task://提交申请
                applyTask();
                break;
        }
    }

    /**
     * 确认申报
     */
    private void applyTask() {
        String str = etTaskName.getText().toString().trim();
        if (str.length() == 0) {
            Utils.showToast(this, "活动名称不能为空");
            return;
        }
        if (subItemBean == null) {
            Utils.showToast(this, "请选择分项");
            return;
        }
        if (voucherData == null) {
            Utils.showToast(this, "请选择活动凭证");
            return;
        }
        if (!NetUtil.isNetworkConnected(this)) {//无网络
            new NoNetDialog(this).show();
            return;
        }
        try {
            btnAskTask.setEnabled(false);
            NewActionHelp.insertPersonActivity(this, etTaskName.getText().toString().trim(), subItemBean.getId(), voucherData, 1, subItemBean.getScore(), new TextHttpResponseHandler() {
                @Override
                public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                    Utils.showToast(AskPersonalTaskActivity.this, "活动申报失败");
                    btnAskTask.setEnabled(true);
                }

                @Override
                public void onSuccess(int i, Header[] headers, String s) {
                    Utils.showToast(AskPersonalTaskActivity.this, "活动申报成功");
                    AskPersonalTaskActivity.this.setResult(1000);
                    finish();
                }
            });
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            btnAskTask.setEnabled(true);
        }
    }

    /**
     * 选择凭证图片
     */
    private void selectImg() {
        Intent intent = new Intent(this, MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // 最大可选择图片数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
        // 选择模式
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
        // 默认选择
        if (selectedPictureAll != null && selectedPictureAll.size() > 0) {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, selectedPictureAll);
        }
        startActivityForResult(intent, REQUEST_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE && data != null) {//选择图片回调
            ArrayList<String> mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            selectedPictureAll.addAll(mSelectPath);
            for (String path : mSelectPath) {
                Log.e("sss", "图片地址---" + path);
                GlideUtil.loadLocalUrl(this, path, imgUploadTestimony, null);
                voucherData = path;
            }
        }
    }

    public void click(SubItemBean subItemBean) {//弹窗点击事件监听
        tvTaskSubItem.setText(subItemBean.getIndexName());
        tvTaskCategory.setText(subItemBean.getKindName());
        tvTaskType.setText(subItemBean.getIndexType());
        tvTaskValue.setText(String.format("%s分", Utils.getScore(subItemBean.getScore())));
        this.subItemBean = subItemBean;
    }

    void showDropPop(View v) {
        View view = LayoutInflater.from(this).inflate(R.layout.login_change_account_dialog, null);
        ListView changeListView = (ListView) view.findViewById(R.id.login_change_account_listview);
        changeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                click(subItemBeanList.get(position));
                moreAccountPup.dismiss();
            }
        });
        changeListView.setFocusable(true);
        changeListView.setFocusableInTouchMode(true);
        changeListView.setCacheColorHint(Color.TRANSPARENT);
        changeListView.setDivider(new ColorDrawable(Color.GRAY));
        changeListView.setDividerHeight(1);
        SubItemAdapter mAdapter = new SubItemAdapter(this, subItemBeanList);
        changeListView.setAdapter(mAdapter);
        moreAccountPup = new PopupWindow(view, v.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT);
        moreAccountPup.setBackgroundDrawable(new BitmapDrawable());
        moreAccountPup.setFocusable(true);
        moreAccountPup.showAsDropDown(v, 0, 20);
    }

    private class SubItemAdapter extends BaseAdapter {

        public List<SubItemBean> params;
        Context mContext;

        private SubItemAdapter(Context context, List<SubItemBean> params) {
            mContext = context;
            this.params = params;
        }

        @Override
        public int getCount() {
            return params == null ? 0 : params.size();
        }

        @Override
        public SubItemBean getItem(int position) {
            return params == null ? null : params.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            DeviceViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new DeviceViewHolder();
                convertView = LayoutInflater.from(mContext).inflate(R.layout.login_change_account_item, parent, false);
                viewHolder.name = (TextView) convertView.findViewById(R.id.login_change_account_tv);
                viewHolder.delete = (ImageView) convertView.findViewById(R.id.login_change_account_delete_tv);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (DeviceViewHolder) convertView.getTag();
            }
            final SubItemBean itemBean = getItem(position);
            viewHolder.name.setText(itemBean.getIndexName());
            viewHolder.name.setPadding(10, 10, 10, 10);
            viewHolder.delete.setVisibility(View.GONE);
            return convertView;
        }

        class DeviceViewHolder {
            public TextView name;
            public ImageView delete;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NewActionHelp.cancel(this);
    }
}
